const axios = require('axios').default;
const log4js = require('log4js');
log4js.configure({
	appenders: { cheese: { type: "file", filename: "cheese.log" } },
	categories: { default: { appenders: ["cheese"], level: "error" } }
});
const logger = log4js.getLogger();
logger.level = "debug";
module.exports = {
	transform(value) {
		logger.debug(`url:${value.config.url} - status:${value.status},code:${value.data ? value.data.code : -999},msg:${value.data ? value.data.msg ? value.data.msg : '暂无' : '暂无'}`);
		let data = {
			code:0,
			data:null,
			msg:'success'
		};
		if(value.status !== 200) {
			data.code = value.status;
			data.msg = '网络错误';
			return data;
		}
		if(!value.data) {
			data.code = -1;
			data.msg = '数据错误';
			return data;
		}
		if(value.data.code === undefined || value.data.code === 102001) {
			data.code = -2;
			data.msg ='可能是登录失效';
			return data;
		}
		data.code = value.data.code;
		data.data = value.data.data;
		data.msg = value.data.msg ? value.data.msg : '无';
		return data;
	},
	async request(url,params = {},method = 'get',session) {
		return await axios.request({
			url:url,
			params:params,
			method:method,
			headers:{
				cookie:session,
				version1:"sPbQBRbP6KbQvhvQkP2Q6ovQTKbPN8AQThvPbf7PNf7",
				accept:"application/json"
			}
		}).then(res =>this.transform(res)).catch(err =>{
			console.log('request error',err);
			return {
				code:-999,
				msg:'请求错误',
				data:null
			}
		});
	},
	async sleep(time = 3000) {
		return new Promise((a,b) =>{
			setTimeout(() =>{
				a()
			},time);
		});
	},
	async postMessage(url,data) {
		await axios.post(url,data);
		console.log('消息推送完成');
		return true;
	}
}